package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-13 15:48
 **/
public class LeetCode300 {
    public static void main(String[] args) {
        LeetCode300 code = new LeetCode300();
        System.out.println(code.lengthOfLIS(new int[]{10,9,2,5,3,7,101,18}));
    }

    //贪心 + 二分
    public int lengthOfLIS(int[] nums) {
        //记录目前最长上升子序列的长度
        int len = 1;
        int n = nums.length;
        //表示长度为 i 的最长上升子序列的末尾元素的最小值
        int[] d = new int[n + 1];
        d[1] = nums[0];
        for (int i = 1; i < n; ++i) {
            if (nums[i] > d[len]) {
                d[++len] = nums[i];
            } else {
                int l = 1;
                int r = len;
                int pos = 0;
                //寻找<nums[i]的第一个数
                //如果找不到说明所有的数都比 nums[i] 大，此时要更新 d[1]，所以这里将 pos 设为 0
                while (l <= r) {
                    int mid = l + r >> 1;
                    if (d[mid] < nums[i]) {
                        pos = mid;
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }

                d[pos + 1] = nums[i];
            }
        }
        return len;
    }

    //动态规划
    /*public int lengthOfLIS(int[] nums) {
        int n = nums.length;

        //dp[i]: 以nums[i]结尾的的最长递增子序列长度
        int[] dp = new int[n];
        int max = 1;
        dp[0] = 1;
        for (int i = 1; i < n; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }

            max = Math.max(max, dp[i]);
        }

        return max;
    }*/

}
